package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class Utils {
    public static WebDriver driver;

    public static WebDriver createDriver(){
        if (driver == null){
            //浏览器配置
            WebDriverManager.edgedriver().setup();
            EdgeOptions options = new EdgeOptions();
            //允许访问所有链接
            options.addArguments("--remote-allow-origins=*");
            options.setPageLoadStrategy(PageLoadStrategy.NORMAL);

            driver = new EdgeDriver(options);
            //设置隐式等待
            WebDriver.Timeouts wait = driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
        }
        return driver;
    }

    public Utils(String url){
        driver = createDriver();
        driver.get(url);

    }

    public void getScreenShot(String str) throws IOException {
        // ./src/test/pics
        //                /2024-12-10/
        //                            test01-17453010.png
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");//SS表示毫秒，因为自动化执行速度是非常快的

        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());

        String fileName = "./src/test/pics/" + dirTime + "/"+ str + "_" + fileTime + ".png";
        System.out.println("filename: "+fileName);
        //截屏
        File screenShot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        // 放到指定位置
        FileUtils.copyFile(screenShot,new File(fileName));

    }


}
